package com.lilosoft.core.utils.commons;

import java.util.Date;

import com.lilosoft.core.cache.JedisRepository;
import com.lilosoft.core.context.SpringContext;
import com.lilosoft.core.exception.MyException;

public class BjbmUtils {
	public static final int EXPIRETIME = 2 * 24 * 60;
	public static String generateBjbm(String parameter) {
		StringBuilder bjbm = new StringBuilder();
		JedisRepository redisUtil = SpringContext.getBean(JedisRepository.class);
		if(StringUtils.isEmpty(parameter)) {
			throw new MyException("生成办件编码时，请求参数有误");
		}
		String prefix = parameter.substring(0,5);
		String bjbmKey = "bjbm"+DateUtils.formatDate(new Date(), "yyMMdd");
		boolean isExists = redisUtil.exists(0, bjbmKey);
		if(!isExists) {
			copyBjbm2Redis(bjbmKey,redisUtil);
		}
		String bjbmValue = redisUtil.incr(0, bjbmKey,EXPIRETIME).toString();
		if(bjbmValue.length()<5) {
			bjbmValue = StringUtils.leftPad(bjbmValue, 5,"0");
		}
		bjbm.append(prefix)
			.append(bjbmKey.substring(4))
			.append(bjbmValue);
		return bjbm.toString();
	}
	//初始化redis中key
	public static void copyBjbm2Redis(String bjbmKey,JedisRepository redisUtil) {
		redisUtil.setInteger(0, bjbmKey, 0, EXPIRETIME);
	}
}
